import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, FormControl} from '@angular/forms';
import {List} from 'linqts';
import {MenuService} from '../../../service/menu.service';
import {Menu} from '../../../entity/menu.model';
import {Router} from '@angular/router';
import {MenuShortcut} from '../../../entity/menu_shortcut.model';
import {MenuFavorite} from '../../../entity/menu_favorite.model';
import {ApplicationService} from '../../../service/application.service';
import {MenuFavoriteService} from '../../../service/menu_favorite.service';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {
  public menuSearchForm: FormGroup;
  public isSearching: boolean = false;
  /**
   * 是否展开所有功能菜单
   *
   * @type {boolean}
   * @memberof MenuComponent
   */
  public openAllMenu: boolean = false;
  /**
   * 是否展开所有功能菜单
   *
   * @type {boolean}
   * @memberof MenuComponent
   */
  public openMenu: boolean = false;
  /**
   * 当前用户可以访问的菜单（没有结构关系）
   *
   * @private
   * @type {Menu[]}
   * @memberof MenuComponent
   */
  private menus: Menu[] = [];

  /**
   * 当前用户可以访问的菜单（没有结构关系）
   *
   * @private
   * @type {Menu[]}
   * @memberof MenuComponent
   */
  public filerMenus: Menu[] = [];


  /**
   * 当前用户可以访问的菜单（存在结构关系）
   *
   * @type {MenuAccess[]}
   * @memberof MenuComponent
   */
  public accesies: Menu[] = [];

  /**
   * 当前用户固定菜单
   *
   * @type {MenuShortcut[]}
   * @memberof MenuComponent
   */
  public shortcuts: MenuShortcut[] = [];
  /**
   * 当前用户固定菜单
   *
   * @type {MenuFavorite[]}
   * @memberof MenuComponent
   */
  public favorites: MenuFavorite[] = [];
  /**
   *
   *
   * @type {Menu}
   * @memberof MenuComponent
   */
  public selectedAccess: Menu;
  /**
   *
   *
   * @type {MenuShortcut}
   * @memberof MenuComponent
   */
  public selectedShortcut: MenuShortcut;
  /**
   *
   *
   * @type {MenuFavorite}
   * @memberof MenuComponent
   */
  public selectedFavorite: MenuFavorite;
  /**
   * 用于拖拽的收藏菜单
   *
   * @type {MenuFavorite}
   * @memberof MenuComponent
   */
  public draggedFavorite: MenuFavorite;


  /**
   * 菜单提示框标题
   *
   * @type {string}
   * @memberof MenuComponent
   */
  public title: string;

  /**
   * 提示框定位的top值
   *
   * @type {number}
   * @memberof MenuComponent
   */
  public top: number;

  /**
   * 是否显示提示框
   *
   * @type {boolean}
   * @memberof MenuComponent
   */
  public showPrompt: boolean = false;
  private timer: any = null;
  private timerL: any = null;

  /**
   * Creates an instance of MenuComponent.
   * @param {FormBuilder} fb
   * @param {MenuService} menuService
   * @param {MenuFavoriteService} menuFavoriteService
   * @param {ApplicationService} application
   * @param {Router} router
   * @memberof MenuComponent
   */
  constructor(
    private fb: FormBuilder,
    private menuService: MenuService,
    private menuFavoriteService: MenuFavoriteService,
    private application: ApplicationService,
    private router: Router) {

    this.menuSearchForm = fb.group({
      menuName: new FormControl()
    });
    this.menuSearchForm.controls['menuName']
      .valueChanges
      .debounceTime(300)
      .distinctUntilChanged()
      .subscribe((menuName: string) => {
        if (menuName && this.menus.length > 0) {
          this.filerMenus = [];
          this.isSearching = true;
          this.menus.forEach(menu => {
            if (menu.menuName.indexOf(menuName) >= 0 && menu.parentId != 0) {
              this.filerMenus.push(menu);
            }
          });
        }
        else {
          this.isSearching = false;
          this.filerMenus = [];
        }
      });
  }

  ngOnInit() {
    // //获取缓存数据的用户id
    this.menuService.getMenuProfilesByUserId(this.application.currentUser.userId).then(res => {
      if (!res) {
        return false;
      }
      this.menus.push(...res.access);
      // console.log(this.menus)
      //加载菜单快捷方式（固定菜单）
      if (res.shortcut != null && res.shortcut.length > 0) {
        let list = new List(res.shortcut);
        let shortcutTemp = list.OrderBy(o => o.shortCutSeq).ToArray();
        this.shortcuts.push(...shortcutTemp);
        if (!this.application.currentMenu) {
          //导航到用户配置的页面
          this.selectedShortcut = this.shortcuts[0];
          this.selectedFavorite = null;
          this.selectedAccess = null;
          //设置当前菜单
          this.application.currentMenu = this.menus.find(o => o.menuId == this.selectedShortcut.menuId);
        }
        this.router.navigate([this.application.currentMenu.menuPath]);
      }
      //加载用户收藏夹
      if (res.favorite != null && res.favorite.length > 0) {
        let list = new List(res.favorite);
        let favoriteTemp = list.OrderBy(o => o.favoriteSeq).ToArray();
        favoriteTemp.forEach(f => {
          let flag = false;
          if (this.shortcuts.find(o => o.menuId == f.menuId)) {
            flag = true;
          }
          if (!flag) {
            this.favorites.push(f);
          }
        });
      }
      //初始化用户可以访问的菜单进行排序
      this.initMenuAccesies(this.menus);
      // console.log(this.menus.find(o =>{o.menuId == 5}))
    })
      .catch(error => {
        console.log('app-menu has error', error);
      });
  }

  /**
   * 初始化用户有访问权限的菜单主要是对菜单进行重新排序
   *
   * @param {Menu[]} menuAccesies
   * @memberof MenuComponent
   */
  initMenuAccesies(menuAccesies: Menu[]) {
    this.accesies = [];
    if (menuAccesies != null && menuAccesies.length > 0) {
      let firstMenus = menuAccesies.filter(o => o.parentId == 0);
      if (firstMenus != null) {
        firstMenus = new List(firstMenus).OrderBy(o => o.menuSeq).ToArray();
        // console.log(firstMenus)
        firstMenus.forEach(menu => {
          //如果菜单是收藏夹中的菜单
          if (this.favorites.find(o => o.menuId == menu.menuId)) {
            menu.isFavorite = true;
          }
          this.accesies.push(menu);
          this.initChildMenuAccesies(menu, menuAccesies);
        });

      }
    }
  }

  initChildMenuAccesies(menu: Menu, menuAccesies: Menu[]) {

    let childrenMenus = menuAccesies.filter(o => o.parentId == menu.menuId);
    if (childrenMenus != null && childrenMenus.length > 0) {
      let list = new List(childrenMenus);
      let childrenTemp = list.OrderBy(o => o.menuSeq).ToArray();
      menu.children = childrenTemp;
      menu.children.forEach(childrenMenu => {
        //如果菜单是收藏夹中的菜单
        if (this.favorites.find(o => o.menuId == childrenMenu.menuId)) {
          childrenMenu.isFavorite = true;
        }
        this.initChildMenuAccesies(childrenMenu, menuAccesies);
      });
    }
  }

  /**
   * 点击用户快捷方式
   *
   * @param {Menu} menu
   * @memberof MenuComponent
   */
  onShortcutSelectedChange(shortcut: MenuShortcut) {
    this.selectedShortcut = shortcut;
    this.selectedFavorite = null;
    //设置当前菜单
    this.application.currentMenu = this.menus.find(o => o.menuId == this.selectedShortcut.menuId);
    this.router.navigate([this.selectedShortcut.menuPath]);
    this.openMenu = false;
    this.openAllMenu = false;
    this.menus.forEach(menu => {
      menu.isShow = false;
    });
  }

  /**
   * 点击用户收藏夹
   *
   * @param {Menu} menu
   * @memberof MenuComponent
   */
  onFavoriteSelectedChange(favorite: MenuFavorite) {
    this.selectedFavorite = favorite;
    this.selectedShortcut = null;
    //设置当前菜单
    this.application.currentMenu = this.menus.find(o => o.menuId == this.selectedFavorite.menuId);
    this.router.navigate([this.selectedFavorite.menuPath]);
    this.openMenu = false;
    this.openAllMenu = false;
    this.menus.forEach(menu => {
      menu.isShow = false;
    });
  }

  /**
   * 点击用户权限菜单
   *
   * @param {Menu} menu
   * @memberof MenuComponent
   */
  onAccessSelectedChange(menu: Menu) {
    this.selectedAccess = menu;
    this.selectedShortcut = null;
    this.selectedFavorite = null;
    //设置当前菜单
    this.application.currentMenu = this.menus.find(o => o.menuId == this.selectedAccess.menuId);
    this.router.navigate([this.selectedAccess.menuPath]);
    this.openMenu = false;
    this.openAllMenu = false;
    this.menus.forEach(menu => {
      menu.isShow = false;
    });
  }

  /**
   * 点击用户权限菜单展开当前项
   *
   * @param {Menu} menuItem
   * @memberof MenuComponent
   */
  onOpenCurrentMenuItem(menu: Menu) {
    menu.isShow = !menu.isShow;
  }

  /**
   * 展示所有菜单页
   *
   * @memberof MenuComponent
   */
  public onOpenAllMenu() {
    this.openAllMenu = !this.openAllMenu;
    this.accesies.forEach(menu => {
      menu.isShow = false;
    });
  }

  public onOpenMenu() {
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.openMenu = true;
    }, 300);
  }

  public onCloseMenu() {
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.openMenu = false;
    }, 100);
  }


  /**
   * 点击添加或移除收藏夹
   *
   * @param {Menu} menu
   * @memberof MenuComponent
   */
  public onFavoriteChecked(menu: Menu) {
    if (menu.isFavorite) {
      let seq = 0;
      if (this.favorites.length > 0) {
        seq = this.favorites.length - 1;
      }
      let newFavorite = new MenuFavorite(
        0,
        this.application.currentUser.userId,
        menu.menuId,
        seq,
        menu.menuName,
        menu.menuSubName,
        menu.menuPath,
        menu.menuIcon
      );
      this.menuFavoriteService
        .create(newFavorite)
        .then(res => {
          //数据库保存成功后添加收藏夹
          if (res) {
            newFavorite.favoriteId = res.favoriteId;
            this.favorites.push(newFavorite);
          }
          else {
            menu.isFavorite = false;
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
    else {
      let index = this.favorites.findIndex(o => o.menuId == menu.menuId);
      if (index >= 0) {
        let removeFavorite = this.favorites[index]
        this.menuFavoriteService
          .batchDelete([removeFavorite.favoriteId])
          .then(res => {
            //数据库移除成功后从收藏夹移除
            if (res) {
              this.favorites.splice(index, 1);
            }
            else {
              menu.isFavorite = true;
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    }
  }

  public onDragStart(event: any, favorite: MenuFavorite) {
    this.draggedFavorite = favorite;
  }

  public onDrop(event: any, favorite: MenuFavorite) {
    let index = this.favorites.findIndex(o => o.favoriteId == favorite.favoriteId);
    let draggedIndex = this.favorites.findIndex(o => o.favoriteId == this.draggedFavorite.favoriteId);
    this.favorites.splice(draggedIndex, 1);
    this.favorites.splice(index, 0, this.draggedFavorite);
    this.menuFavoriteService.batchUpdate(this.favorites)
      .catch(err => {
        console.log(err);
      });
  }

  public onDragEnd(event: any) {
    this.draggedFavorite = null;
  }


  /**
   * 鼠标移入菜单
   *
   * @param {any} $event
   * @param {any} item
   * @memberof MenuComponent
   */
  enterMenu($event, item) {
    this.title = item.menuName
    this.top = $event.toElement.offsetTop - $event.toElement.parentElement.scrollTop;
    clearTimeout(this.timerL);
    this.timerL = setTimeout(() => {
      this.showPrompt = true;
    }, 300);
  }


  /**
   * 鼠标移出菜单
   *
   * @memberof MenuComponent
   */
  leaveMenu() {
    clearTimeout(this.timerL);
    this.timerL = setTimeout(() => {
      this.showPrompt = false;
    }, 100);
  }
}
